<!--
 * @Autor: Ruohong Yu
 * @Date: 2021-11-27 16:40:05
 * @LastEditors: Ruohong Yu
 * @LastEditTime: 2021-12-23 12:11:51
 * @Description: 头部导航栏
 * @FilePath: \mimalld:\桌面\作业\软件工程\前端\front_regit\src\components\NavHeader.vue
-->

<template>
  <div class="header">
    <div class="left" @click="collapse">
      <i :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'" />
    </div>
    <div class="right">
      <span><i class="el-icon-search" /></span>
      <!-- WebSocket数据渲染 -->
      <el-popover
        placement="bottom-end"
        trigger="click"
        class="ins"
      >
        <el-row v-if="messagelist===''" style="margin-top: 190px; text-align: center;vertical-align: middle;">
          暂无消息
        </el-row>
        <el-row v-else>
          <div style="color: dodgerblue; cursor: pointer;float: right;margin-right: 15px;margin-top: 10px;" @click="readallmessage()">一键已读</div>
          <div style="padding-top: 20px;" />
          <el-row style="padding-left:25px; margin-top:25px; border-top: 1px solid rgb(221, 221, 221);" />
          <el-row
            v-for="(messagedetail, index) in messagelist"
            :key="index"
          >
            <el-row style="padding-left:25px; padding-bottom:25px; padding-top:25px; border-bottom: 1px solid rgb(221, 221, 221);">
              <el-col :span="3" style="float: left;">
                <el-avatar size="large" :src="messagedetail.projectLogoUrl" />
              </el-col>
              <el-col :span="18" style="margin-left: 20px;">
                <div v-if="messagedetail.message.messageStatus === 1">
                  <!-- <span class="text4">{{ getuserinformation(messagedetail.message.userId) }}</span> -->
                  <!-- <span>邀请你进入项目：</span> -->
                  <span>项目：</span>
                  <span>{{ messagedetail.message.projectName }}</span>
                  <span>期待你的加入！</span>
                </div>
                <div v-if="messagedetail.message.messageStatus === 2">
                  <span>项目：</span>
                  <span>{{ messagedetail.message.projectName }}</span>
                  <span>初审通过</span>
                </div>
                <div v-if="messagedetail.message.messageStatus === 3">
                  <span>项目：</span>
                  <span>{{ messagedetail.message.projectName }}</span>
                  <span>二审通过</span>
                </div>
                <div v-if="messagedetail.message.messageStatus === 4">
                  <span>项目：</span>
                  <span>{{ messagedetail.message.projectName }}</span>
                  <span>提交了结题申请</span>
                </div>
                <div v-if="messagedetail.message.messageStatus === 5">
                  <span>项目：</span>
                  <span>{{ messagedetail.message.projectName }}</span>
                  <span>结题申请通过</span>
                </div>
                <p style="margin-top:10px;font-size: 13px;color: #999;">{{ messagedetail.message.messageTime | formatDate }}</p>
              </el-col>
            </el-row>
          </el-row>
        </el-row>
        <span slot="reference"><i class="el-icon-bell" /></span>
      </el-popover>
      <span v-if="messagelist!==''" class="redmes" />
      <span class="user">
        <div class="tx">
          <el-avatar size="small" :src="userimg" />
        </div>
        <div class="name">
          <ul class="nav">
            <li class="drop-down">
              <a href="#">{{ username }}</a>
              <ul class="drop-down-content">
                <li @click="gocenter()"><span class="out">个人中心</span></li>
                <li @click="logout()"><span class="out">退出登录</span></li>
              </ul>
            </li>
          </ul>
        </div>
      </span>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import crypto from '../crypto/crypto'
export default {
  name: 'NavHeader',
  filters: {
    /**
     * @description: 时间转换
     * @param {*} value
     * @return {*}
     * @author: Hongting Yuan
     */
    formatDate: function(value) {
      const date = new Date(value)
      const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
  },
  data() {
    return {
      path: '',
      ws: {},
      isCollapse: false,
      username: this.$store.getters.getroleName,
      userimg: '',
      userId: this.$store.getters.getuserId,
      messagelist: [],
      messageidlist1: { // 批量已读格式
        messageIdList: []
      }
    }
  },
  created() {
    this.$store.commit('setisCollapse', this.isCollapse)
    this.getuserimg()
    this.init()
  },
  destroyed() {
    this.ws.onclose()
  },
  methods: {

    /**
     * @description: 一键已读
     * @param {*}
     * @return {*}
     * @author: Hongting Yuan
     */
    readallmessage() {
      this.$confirm('已读所有消息，将不再提示, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get('/msg/haveReadUserId/', { params: { userId: this.userid }})
          .then((res) => {
            // if (res.data.code === 200) {
            //   this.$message({
            //     message: res.data.msg,
            //     type: 'success'
            //   })
            // }
            this.messagelist = ''
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
          .catch(err => {
            console.error(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * @description: websocket连接
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    init() {
      this.path = 'ws://123.60.224.189:8080' + `/webServer/${this.userId}`
      this.ws = new WebSocket(this.path)

      // 监听是否连接成功
      this.ws.onopen = () => {
        console.log('连接状态：' + this.ws.readyState)
        this.ws.send('连接成功')
        heartCheck.start()
      }

      // 接听服务器发回的信息并处理展示
      this.ws.onmessage = (res) => {
        console.log('接收到来自服务器的消息：')
        var alist = []
        alist = JSON.parse(res.data).list
        console.log('this.getlist', alist)
        var co = 0
        for (var i = alist.length - 6; i <= alist.length - 1; i++) {
          this.messagelist[co] = alist[i]
          co++
        }

        heartCheck.start()
      }

      // 监听连接关闭事件
      this.ws.onclose = () => {
        console.log('连接状态：' + this.ws.readyState)
      }

      // 监听并处理error事件
      this.ws.onerror = function(error) {
        console.log(error)
      }

      // 心跳检测，检测客户端和服务端是否处于正常连接的状态
      var heartCheck = {
        timeout: 3000,
        timeoutObj: null,
        serverTimeoutObj: null,
        start: function() {
          console.log('start')
          var self = this
          this.timeoutObj && clearTimeout(this.timeoutObj)
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
          this.timeoutObj = setTimeout(function() {
          // 每隔3秒发送一个心跳，后端收到后，返回一个心跳消息，
            console.log('55555')
            this.ws.send('heartCheck')
            self.serverTimeoutObj = setTimeout(function() {
              console.log(111)
              console.log(this.ws)
              this.ws.close()
            // createWebSocket();
            }, self.timeout)
          }, this.timeout)
        }
      }
    },
    acceptMessage() {
      console.log('message')
    },
    collapse() {
      this.isCollapse = !this.isCollapse
      this.$store.commit('setisCollapse', this.isCollapse)
      this.$emit('changecollapse', this.isCollapse)
    },

    /**
     * @description: 退出登录
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    logout() {
      axios
        .get('user/logout')
        .then(() => {
          this.$message.info('退出成功')
        })
        .catch((error) => {
          console.log(error)
        })
      // 清空token
      window.sessionStorage.clear()
      this.$router.push('/')
      window.location.reload()
    },
    gocenter() {
      this.$router.push('/' + crypto.set(38))
    },
    getuserimg() {
      axios.get('/user/getImage', { params: { userId: this.userId }})
        .then((res) => {
          this.userimg = res.data.data
        })
        .catch(err => {
          console.error(err)
        })
    }
  }
}
</script>
<style lang='scss'>
* {
  margin: 0;
  padding: 0;
}
.ins{
  width:400px;
  height: 400px;
  overflow-x: hidden;
  overflow-y: auto;
}
.el-icon-bell{
  cursor: pointer;
}
ul {
  list-style: none;
  font-weight: 200;
  z-index: 2147483647;
}
.nav > li {
  float: left;
  z-index: 2147483647;
}
ul a {
  display: block;
  font-size: 15px;
  text-decoration: none;
  width: 100px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  color: #5c5c5c;
  z-index: 2147483647;
}

.out{
  display: block;
  cursor: pointer;
  font-size: 15px;
  text-decoration: none;
  width: 100px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  color: #5c5c5c;
  z-index: 2147483647;
}
.drop-down-content > li:last-child span {
  border-radius: 0px 0px 5px 5px;
  z-index: 2147483647;
}
.drop-down {
  height: 40px;
  z-index: 2147483647;
}
.drop-down-content {
  padding: 0;
  opacity: 0;
  border-radius: 0px 0px 5px 5px;
  background-color: rgb(200, 229, 255);
  height: 100px;
  overflow: hidden;
  transition: all 1s ease;
  position: relative;
  z-index: 2147483647;
}
.drop-down-content li:hover span {
  background-color: #d3d3d3;
  opacity: 1;
  z-index: 2147483647;
}
.nav .drop-down:hover .drop-down-content {
  opacity: 1;
  height: 100px;
  z-index: 2147483647;
}

.header {
  width: 100%;
  height: 50px;
  border: 1px solid;
  border-color: #e9e9e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  .left {
    display: inline-block;
    font-size: 30px;
    color: #5c5c5c;
    i {
      width: 40px;
      height: 40px;
    }
  }
  .right {
    position: relative;
    display: inline-block;
    height: 100%;
    font-size: 30px;
    color: #5c5c5c;
    i {
      width: 40px;
      height: 40px;
    }
    .redmes {
      position: absolute;
      display: inline-block;
      width: 8px;
      height: 8px;
      background-color: red;
      border-radius: 50%;
      top: 17px;
      left: 60px;
    }
    .user {
      display: inline-block;
      width: 150px;
      .tx {
        display: inline-block;
        width: 30px;
        height: 30px;
        background: url("../assets/img/logo.png") no-repeat center;
        background-size: contain;
      }
      .name{
        display: inline-block;
        position: relative;
        top: 5px;
      }
    }
  }
}
</style>
